using zhwy.saas.api.Entity.Sys;
using zhwy.saas.api.Extensions.Log;
using zhwy.saas.api.Repository;
using zhwy.saas.api.Services.Sinterface.Sys;

namespace zhwy.saas.api.Services.Sys
{
    /// <summary>
    /// 系统菜单服务实现
    /// </summary>
    public class SysMenuService : BaseService<MenusEntity>, ISysMenuService
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository">菜单仓储接口</param>
        /// <param name="logger">日志服务</param>
        public SysMenuService(IBaseRepository<MenusEntity> repository, ILogExt logger)
            : base(repository, logger)
        {
        }

        /// <summary>
        /// 获取菜单树形结构
        /// </summary>
        /// <returns>菜单树</returns>
        public async Task<List<MenusEntity>> GetMenuTreeAsync()
        {
            var allMenus = await _repository.GetAllAsync();
            return BuildMenuTree(allMenus, 0); // 假设根菜单的ParentId为0
        }

        /// <summary>
        /// 获取用户的菜单权限
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户有权限的菜单列表</returns>
        public async Task<List<MenusEntity>> GetUserMenusAsync(long userId)
        {
            // TODO: 实现用户菜单权限查询，需要关联角色和权限表
            var allMenus = await _repository.GetListAsync(m => m.Status == 1);
            return BuildMenuTree(allMenus, 0);
        }

        /// <summary>
        /// 获取角色的菜单权限
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns>角色有权限的菜单列表</returns>
        public async Task<List<MenusEntity>> GetRoleMenusAsync(long roleId)
        {
            // TODO: 实现角色菜单权限查询，需要关联权限表
            var allMenus = await _repository.GetListAsync(m => m.Status == 1);
            return BuildMenuTree(allMenus, 0);
        }

        /// <summary>
        /// 更新菜单状态
        /// </summary>
        /// <param name="menuId">菜单ID</param>
        /// <param name="status">新状态</param>
        /// <returns>是否更新成功</returns>
        public async Task<bool> UpdateStatusAsync(long menuId, int status)
        {
            var menu = await _repository.GetByIdAsync(menuId);
            if (menu == null)
                return false;

            menu.Status = status;
            return await _repository.UpdateAsync(menu);
        }

        /// <summary>
        /// 构建菜单树
        /// </summary>
        /// <param name="menus">所有菜单列表</param>
        /// <param name="parentId">父级ID</param>
        /// <returns>树形结构的菜单列表</returns>
        private List<MenusEntity> BuildMenuTree(List<MenusEntity> menus, long parentId)
        {
            return menus
                .Where(m => m.Pid == parentId)
                .Select(m =>
                {
                    m.Children = BuildMenuTree(menus, m.Id);
                    return m;
                })
                .OrderBy(m => m.Sort)
                .ToList();
        }
    }
}